﻿using project1113.Wrold;
using System;
using project1113;
using System.Speech.Recognition;
using static project1113.MainWindow;
using project1113.FSM;

namespace project1113.states
{
    public class EmergenceState: FsmState
    {

        SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine();
        bool? isDown = null;
        FsmState _laststate;

       public EmergenceState(FsmState lastState) : base("emergency") 
        {
            _laststate = lastState;
        }
        public override void Init()
        {
            WorldModel.CurrentWorld.SpeechRecoginzer.Mode = SpeechRecognizeMode.mode_Exigence;

            WorldModel.CurrentWorld.TTS.Speak("紧急模式");
            // 创建一个自定义语法，包括唤醒词
            Choices wakeUpWords = new Choices(new string[] { "我跌倒了" , "我没事" });
           
            GrammarBuilder grammarBuilder = new GrammarBuilder(wakeUpWords);

            Grammar grammar = new Grammar(grammarBuilder);

            recognizer.LoadGrammar(grammar);

            // 注册事件处理程序以处理语音识别结果
            recognizer.SpeechRecognized += (s, e) =>
            {
                if (e.Result != null )
                {
                    if(e.Result.Text== "我跌倒了")
                    {
                        isDown = true;
                    }

                    else if (e.Result.Text == "我没事")
                    {
                        isDown = false;
                    }

                    Console.WriteLine("唤醒成功！");
                    // 在这里可以执行你的操作，例如打开应用程序或触发其他操作。
                }
            };

            // 启动语音识别引擎
            recognizer.SetInputToDefaultAudioDevice();
            //recognizer.RecognizeAsync(RecognizeMode.Multiple);
            recognizer.RecognizeAsync(RecognizeMode.Multiple);

        }
        public override void DoSomething()
        {
            DisplayHelper.LoadPage("Emergence");
        }
        public override FsmState GetNextState()
        {
            if (isDown != null)
            {
                recognizer.RecognizeAsyncStop();
                if (isDown == true)
                {
                    return new UnsafeState(_laststate);
                }
                else
                {
                    return new SafeState(_laststate);
                }
            }
            else { 
                return this;
            }

        }

    }
}
